import {ref} from 'vue'
import {defineStore} from 'pinia'
import {loginAPI} from '@/apis/user'
import {useCartStore} from '@/stores/cartStore'
import {mergeCartAPI} from '@/apis/cart'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref({})
  const cartStore = useCartStore()
  // 登录 获取用户信息
  const getUserInfo = async ({ account, password }) => {
    const res = await loginAPI({ account, password })
    userInfo.value = res.result
    //登录成功后，合并购物车
    const list= cartStore.cartList.map(item=>{
      return {
        skuId: item.skuId,
        selected : item.selected,
        count : item.count
      }})
      await mergeCartAPI(list)
      cartStore.getCartList()
  }

  // 退出登录
  const clearUserInfo = () => {
    userInfo.value = {}
    cartStore.clearCart()
  }
  return {
    userInfo,
    getUserInfo,
    clearUserInfo
  }
},{ persist: true,}

)